<template>
  <div ref="content">
    <a-card :bordered="false">
      <a-page-header
        style="border-bottom: 1px solid rgb(235, 237, 240); padding: 8px 16px"
        title=""
      />
      <split splitHeight="100%" leftWidth="220">
        <template slot="paneL">
          <!-- 部门树 -->
          <dept-tree
            ref="deptTree"
            :deptOptions="deptOptions"
            :defalutExpandedKeys="expandedKeys"
            @setDataOptionInfo="setDataOptionInfo"
            @select="clickDeptNode"
            :defaultSelectedKeys="defaultKeys"
          />
        </template>
        <template slot="paneR">
          <a-divider />
          <a-row>
            <a-col :span="24">
              <a-table
                bordered
                size="middle"
                style="margin-top: 8px"
                :data-source="dataSource"
                :columns="deptColumns"
                :pagination="false"
              >
                <template
                  v-for="col in [
                    'calls',
                    'newCus',
                    'genjin',
                    'toHome',
                    'jinjian',
                    'shouru',
                  ]"
                  :slot="col"
                  slot-scope="text, record"
                >
                  <div :key="col">
                    <a-input
                      style="margin: -5px 0"
                      :value="text"
                      @change="(e) => handleChange(e.target.value, record, col)"
                    />
                  </div>
                </template>
              </a-table>
            </a-col>
            <a-col :span="24" style="text-align: center; margin-top: 10px">
              <a-button type="primary" @click="handleAddDeptTarget()"
                >保存配置</a-button
              >
            </a-col>
            <a-col :span="24">
              <advance-table
                :columns="columns"
                :data-source="list"
                :title="tableTitle"
                :loading="loading"
                rowKey="id"
                size="middle"
                tableKey="system-user-SysUserIndex-table"
                @change="handleTableChange"
                @refresh="getList"
                :format-conditions="true"
                :pagination="{
                  current: queryParam.pageNum,
                  pageSize: queryParam.pageSize,
                  total: total,
                  showSizeChanger: true,
                  showLessItems: true,
                  showQuickJumper: true,
                  showTotal: (total, range) =>
                    `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
                  onChange: changeSize,
                  onShowSizeChange: onShowSizeChange,
                }"
                :scroll="{ x: '100%' }"
              >
                <span slot="status" slot-scope="{ record }">
                  <a-badge
                    :status="record.status == '0' ? 'processing' : 'error'"
                    :text="statusFormat(record)"
                  />
                </span>

                <span slot="name" slot-scope="{ text, record, index }">
                  <a @click="onClickRow(record, index)">
                    <a-avatar
                      :style="{ backgroundColor: getRandomColor(index) }"
                      style="color: #fff"
                    >
                      {{ getShowName(text) }}
                    </a-avatar>
                    {{ text }}
                  </a>
                </span>
                <span slot="createTime" slot-scope="text, record">
                  {{ parseTime(record.createTime) }}
                </span>

                <span slot="operation" slot-scope="{ record }">
                  <a @click="handleSetUserTargetSet(record)"> 编辑 </a>
                </span>
              </advance-table>
            </a-col>
          </a-row>
          <!-- 条件搜索 -->

          <!-- 增加修改 -->

          <!-- 编辑用户,单独封装了组件 -->

          <set-user-target
            v-if="setUserTargeOpen"
            ref="setUserTarget"
            :userId="userId"
            :userName="userName"
            @close="setUserTargeOpen = false"
          />
        </template>
      </split>
    </a-card>
  </div>
</template>

<script>
import {
  listUser,
  delUser,
  exportUser,
  importTemplate,
  findListUserBycompanyId,
} from "@/api/system/user";
import { listBizDeptTarget, addBizDeptTarget } from "@/api/biz/bizDeptTarget";
import { listDeptTree } from "@/api/system/dept";
import SetUserTarget from "./modules/SetUserTarget";
import DeptTree from "./modules/DeptTree";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import Split from "@/components/pt/split/Index";
export default {
  name: "User",
  components: {
    AdvanceTable,
    Split,
    DeptTree,
    SetUserTarget,
  },
  data() {
    return {
      visible: false,
      zyUserId: "",
      zyUserList: [],
      consultUserId: "",
      zyvisible: false,
      genjinuser: 0,
      confirmLoading: false,
      showAddModal: false,
      showEditModal: false,
      showJieDanEditModal: false,
      showResetPassword: false,
      list: [],
      colorList: ["#F38709", "#813AFD", "#00C4AA", "#4B7AEE"],
      tableTitle: "业务列表",
      selectedRowKeys: [],
      selectedRows: [],
      setUserTargetOpen: false,
      userId: "",
      userName: "",
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      defaultKeys: [],
      ids: [],
      userNames: [],
      expandedKeys: [],
      loading: false,
      total: 0,
      // 状态数据字典
      statusOptions: [],
      sexOptions: [],
      userTypeOptions: [],
      deptCheckedValue: {},
      // 部门树选项
      deptOptions: [],
      // 客户类型字典
      customerTypeOptions: [],
      // 公司信息
      companyList: [],
      // 业务类型
      busTypeOptions: [],
      // 日期范围
      dateRange: [],
      // treeData
      bizDeptTargetList: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      deptTargetSet: {},
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      deptColumns: [
        {
          title: "部门业绩目标",
          dataIndex: "deptMuBiao",
          align: "center",
          width: "15%",
          key: "deptMuBiao",
        },
        {
          title: "拨打电话(通)",
          dataIndex: "calls",
          scopedSlots: { customRender: "calls" },
          align: "center",
          width: "12%",
          key: "calls",
        },
        {
          title: "新增客户(位)",
          dataIndex: "newCus",
          scopedSlots: { customRender: "newCus" },
          align: "center",
          width: "12%",
          key: "newCus",
        },
        {
          title: "跟进客户(次)",
          dataIndex: "genjin",
          scopedSlots: { customRender: "genjin" },
          align: "center",
          width: "12%",
          key: "genjin",
        },
        {
          title: "邀约上门(位)",
          dataIndex: "toHome",
          scopedSlots: { customRender: "toHome" },
          align: "center",
          width: "12%",
          key: "toHome",
        },
        {
          title: "进件(笔)",
          dataIndex: "jinjian",
          scopedSlots: { customRender: "jinjian" },
          align: "center",
          width: "12%",
          key: "jinjian",
        },
        {
          title: "收入金额(元)",
          dataIndex: "shouru",
          scopedSlots: { customRender: "shouru" },
          align: "center",
          width: "12%",
          key: "shouru",
        },
      ],
      columns: [
        {
          title: "姓名",
          dataIndex: "name",
          width: "180px",
          scopedSlots: { customRender: "name" },
        },
        {
          title: "部门",
          dataIndex: "sysDept.deptName",
          ellipsis: true,
          width: "180px",
        },
        {
          title: "状态",
          dataIndex: "status",
          scopedSlots: { customRender: "status" },
          align: "center",
          width: "120px",
        },
        {
          title: "入职时间",
          ellipsis: true,
          sorter: true,
          width: "180px",
          dataIndex: "createTime",
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "operation",
          width: "100px",
          scopedSlots: { customRender: "operation" },
          align: "center",
        },
      ],
      dataSource: [],
      setUserTargeOpen: false,
    };
  },
  filters: {},
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("user_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getDicts("sys_user_type").then((response) => {
      this.userTypeOptions = response.data;
    });
    this.getDicts("customer_type").then((response) => {
      this.customerTypeOptions = response.data;
    });
    this.getDicts("bus_type").then((response) => {
      this.busTypeOptions = response.data;
    });
    this.getCompanyInfos({}).then((res) => {
      this.companyList = res.data;
    });
  },
  computed: {},
  watch: {},
  methods: {
    handleDeptTargetSet() {
      const params = { deptId: this.queryParam.deptId };
      listBizDeptTarget(params).then((res) => {
        this.bizDeptTargetList = res.data;
        this.dataSource = res.data;
        this.deptTargetSet = {
          id: res.data[0].id,
          dCalls: res.data[0].calls,
          dAddCus: res.data[0].newCus,
          dGenjins: res.data[0].genjin,
          dGoHome: res.data[0].toHome,
          dJinjians: res.data[0].jinjian,
          dShouru: res.data[0].shouru,
          wCalls: res.data[1].calls,
          wAddCus: res.data[1].newCus,
          wGenjins: res.data[1].genjin,
          wGoHome: res.data[1].toHome,
          wJinjians: res.data[1].jinjian,
          wShouru: res.data[1].shouru,
          mCalls: res.data[2].calls,
          mAddCus: res.data[2].newCus,
          mGenjins: res.data[2].genjin,
          mGoHome: res.data[2].toHome,
          mJinjians: res.data[2].jinjian,
          mShouru: res.data[2].shouru,
        };
      });
    },
    handleChange(value, record, column) {
      console.log("789", value, record, column);
      if (record.deptMuBiao === "日") {
        if (column === "calls") {
          this.deptTargetSet.dCalls = value;
          this.dataSource[0].calls = value;
        }
        if (column === "newCus") {
          this.deptTargetSet.dAddCus = value;
          this.dataSource[0].newCus = value;
        }
        if (column === "genjin") {
          this.deptTargetSet.dGenjins = value;
          this.dataSource[0].genjin = value;
        }
        if (column === "toHome") {
          this.deptTargetSet.dGohome = value;
          this.dataSource[0].toHome = value;
        }
        if (column === "jinjian") {
          this.deptTargetSet.dJinjians = value;
          this.dataSource[0].jinjian = value;
        }
        if (column === "shouru") {
          this.deptTargetSet.dShouru = value;
          this.dataSource[0].shouru = value;
        }
      }
      if (record.deptMuBiao === "周") {
        if (column === "calls") {
          this.deptTargetSet.wCalls = value;
          this.dataSource[1].calls = value;
        }
        if (column === "newCus") {
          this.deptTargetSet.wAddCus = value;
          this.dataSource[1].newCus = value;
        }
        if (column === "genjin") {
          this.deptTargetSet.wGenjins = value;
          this.dataSource[1].genjin = value;
        }
        if (column === "toHome") {
          this.deptTargetSet.wGohome = value;
          this.dataSource[1].toHome = value;
        }
        if (column === "jinjian") {
          this.deptTargetSet.wJinjians = value;
          this.dataSource[1].jinjian = value;
        }
        if (column === "shouru") {
          this.deptTargetSet.wShouru = value;
          this.dataSource[1].shouru = value;
        }
      }
      if (record.deptMuBiao === "月") {
        if (column === "calls") {
          this.deptTargetSet.mCalls = value;
          this.dataSource[2].calls = value;
        }
        if (column === "newCus") {
          this.deptTargetSet.mAddCus = value;
          this.dataSource[2].newCus = value;
        }
        if (column === "genjin") {
          this.deptTargetSet.mGenjins = value;
          this.dataSource[2].genjin = value;
        }
        if (column === "toHome") {
          this.deptTargetSet.mGohome = value;
          this.dataSource[2].toHome = value;
        }
        if (column === "jinjian") {
          this.deptTargetSet.mJinjians = value;
          this.dataSource[2].jinjian = value;
        }
        if (column === "shouru") {
          this.deptTargetSet.mShouru = value;
          this.dataSource[2].shouru = value;
        }
      }
    },
    handleAddDeptTarget() {
      this.deptTargetSet.deptId = this.queryParam.deptId;
      addBizDeptTarget(this.deptTargetSet).then((response) => {
        this.handleDeptTargetSet();
        this.$message.success("保存设置成功", 3);
      });
    },
    findListUserBycompanyId() {
      findListUserBycompanyId().then((res) => {
        this.zyUserList = res.data;
      });
    },
    showModalzy() {
      this.findListUserBycompanyId();
      this.zyvisible = true;
      this.genjinuser = 0;
    },
    showModalzyConsult() {
      this.findListUserBycompanyId();
      this.zyvisible = true;
      this.genjinuser = 1;
    },
    handleOk(e) {
      this.confirmLoading = true;
      setTimeout(() => {
        this.zyvisible = false;
        this.confirmLoading = false;
        const userIds = this.ids;
        if (userIds.length > 1) {
          this.$error({
            title: "错误提示！",
            content: "只能选择一条数据！",
          });
          return;
        }
      }, 2000);
    },
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.zyvisible = false;
    },

    // 公司筛选
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    importTemplate(expanded, record) {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      listDeptTree("0", 3).then((response) => {
        this.deptOptions = response.data;
        this.defaultKeys[0] = this.deptOptions[0].id;
        this.queryParam.deptId = this.deptOptions[0].id;
        // console.log("deptInfo", this.deptOptions, this.deptOptions[0].id);
        this.handleDeptTargetSet();
        this.getExpandedKeys(this.deptOptions, 2);
      });
    },
    getExpandedKeys(nodes, expandLevel) {
      if (expandLevel > 1) {
        // 最后一层不展开
        if (nodes != null) {
          nodes.forEach((node) => {
            this.expandedKeys.push(node.id);
            expandLevel = expandLevel - 1;
            return this.getExpandedKeys(node.children, expandLevel);
          });
        }
      }
    },
    // 客户类型字典翻译
    customerTypeFormat(customerType) {
      if (customerType) {
        return this.selectDictLabel(this.customerTypeOptions, customerType);
      } else {
        return "";
      }
    }, // 客户类型字典翻译
    busTypeFormat(row) {
      if (row.busType) {
        return this.selectDictLabel(this.busTypeOptions, row.busType);
      } else {
        return "";
      }
    },
    companyFormat(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].id === "" + value) {
          actions.push(datas[key].companyName);
          return true;
        }
      });
      return actions.join("");
    },
    companyBalanceFormat(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].id === "" + value) {
          actions.push(datas[key].balance);
          return true;
        }
      });
      return actions.join("");
    },
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    userTypeFormat(row) {
      return this.selectDictLabel(this.userTypeOptions, row.userType);
    },
    /** 查询定时任务列表 */
    getList() {
      this.showAddModal = false;
      this.showEditModal = false;
      this.loading = true;
      listUser(this.addDateRange(this.queryParam, this.dateRange)).then(
        (response) => {
          this.list = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      };
      this.handleQuery();
    },
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.userNames = this.selectedRows.map((item) => item.name);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    clickDeptNode(node) {
      this.queryParam.deptId = node.$options.propsData.eventKey;
      this.deptCheckedValue.ids = node.$options.propsData.eventKey;
      this.tableTitle = node.$options.propsData.label;
      if (node.$options.propsData.dataRef.attributes.deptType === "dept") {
        this.deptCheckedValue = {
          ids: node.$options.propsData.eventKey,
          names: node.$options.propsData.label,
        };
      } else {
        this.deptCheckedValue = {};
      }
      console.log(this.deptCheckedValue);
      this.handleDeptTargetSet();
      this.getList();
    },
    handleAdd() {
      this.showAddModal = true;
    },
    handleSetUserTargetSet(value) {
      this.userId = value.id;
      this.userName = value.name;
      this.setUserTargeOpen = true;
      this.$nextTick(() => this.$refs.setUserTarget.handleAdd());
    },
    handleUpdate(record, ids) {
      this.showEditModal = true;
      this.$nextTick(() =>
        this.$refs.sysUserEditForm.handleUpdate(record, ids)
      );
    },
    handleJieDanUpdate(record, ids) {
      this.showJieDanEditModal = true;
      this.$nextTick(() =>
        this.$refs.sysUserJieDanEditForm.handleJieDanUpdate(record, ids)
      );
    },
    handleResetPwd(record) {
      this.showResetPassword = true;
      this.$nextTick(() => this.$refs.resetPassword.handleResetPwd(record));
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this;
      const userIds = row.id || this.ids;
      const userNames = row.name || this.userNames;
      this.$confirm({
        title: "确认删除所选中数据?",
        content: "当前选中编号为" + userNames + "的数据",
        onOk() {
          return delUser(userIds).then(() => {
            that.onSelectChange([], []);
            that.getList();
            that.$message.success("删除成功", 3);
          });
        },
        onCancel() {},
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      this.$confirm({
        title: "是否确认导出?",
        content: "此操作将导出当前条件下所有数据而非选中数据",
        onOk() {
          return exportUser(that.queryParam).then((response) => {
            that.download(response.msg);
            that.$message.success("导出成功", 3);
          });
        },
        onCancel() {},
      });
    },
    getRandomColor(index) {
      // const randomValue = Math.round(Math.random() * 3)
      return this.colorList[index % 4];
    },
    getShowName(name) {
      if (name.length > 2) {
        name = name.substring(name.length - 2);
      }
      return name;
    },
    onClickRow(record, index) {
      this.handleUpdate(record, "");
    },
    setDataOptionInfo(treeDataOption) {
      this.deptOptions = treeDataOption;
    },
    handleTableChange(pagination, filters, sorter) {
      if (
        sorter.field !== undefined &&
        sorter.field !== null &&
        sorter.field !== ""
      ) {
        this.queryParam.orderByColumn = "t." + sorter.field;
        this.queryParam.isAsc = sorter.order;
      }
      this.getList();
    },
  },
};
</script>
<style lang="less" scoped>
.ant-divider-horizontal {
  margin: 0;
  background: rgb(235, 237, 240);
}
.demo-split {
  height: 200px;
}
.demo-split-pane {
  padding: 10px;
}
.ant-avatar {
  font-size: 12px;
  border-radius: 4px;
  vertical-align: middle;
  margin-right: 8px;
}

/deep/.ant-table-body {
}
/deep/.ant-table-placeholder {
  // 将暂无数据提示隐藏，否则没有数据时将表格高度制定导致暂无数据挤到最底下
  display: none;
}
</style>
